/**
 *添加设备
 */
'use strict';


const operationRecord = require("../sys/operationRecordAction");
const Transaction = require('../../libs/DB/Transaction');
const _ = require("underscore");
const {client} = require("../../../server/libs/Redis/RedisClient");


module.exports = async function (params) {
    let transaction = new Transaction()
    try {
        await transaction.beginTransaction();
        let result = await transaction.query(`SELECT df,device_no AS deviceNo,cpdm.measure_type AS measureType FROM device_file df INNER JOIN cost_plan_device_mid cpdm ON cpdm.device_id = df.device_id  WHERE df.device_id = ? AND df.delete_sign = 1 AND df.domain_id = ?`,[params.deviceId,params.userDomainId]);
        if(result.length === 0 ) throw {message:"未找到修改的设备。"};
        if(params.measureList.length > 0){
            let updateSql = ``
            const multi = client.multi();
            let measureObj = _.groupBy(params.measureList,"measureType");
            for(const measure of result){
                if(measureObj[measure.measureType]){
                    updateSql += `UPDATE cost_plan_device_mid SET ladder_base = ${measureObj.ladderBase} WHERE device_id = ${params.deviceId} AND measure_type = ${measure.measureType};`
                    multi.hmset(`deviceInfo-${measure.measureType}-${measure.deviceNo}`,{accumulate:measure.ladderBase});
                }
            }
            await transaction.query(updateSql);
            multi.exec();
        }else{
          throw {message:"缺少设定设备初始值的参数。"}
        }
        await transaction.commit();
        await operationRecord(params);
        return { success: true };
    }catch (e){
        await transaction.rollback();
        return {success:false,message:e.message};
    }
};
